import React, {useEffect, useState} from "react";
import {Divider, message} from "antd";
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc"
dayjs.extend(utc)
import {addLend} from "@/pages/m/Lend/service";
import {Button, DatePicker, Form, Grid, Input, NumberKeyboard, Toast} from "antd-mobile";
import type {FormInstance} from "antd-mobile/es/components/form";
import {isNaN} from "lodash";
import LendLogs from "@/pages/m/LendLogs";
import {HandPayCircleOutline} from "antd-mobile-icons";

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields: any) => {
  const hide = message.loading('正在处理...');

  try {
    const res = await addLend({...fields});
    if(res && res.status === "done"){
      hide();
      Toast.show({
        content: res.message,
        icon: "success"
      })
      return true;
    }else {
      hide()
      Toast.show({
        content: res.message,
        icon: "fail"
      })
      return false;
    }
  } catch (error) {
    hide();
    Toast.show({
      content: "记录失败请重试",
      icon: "fail"
    });
    return false;
  }
};

const OwnForm: React.FC = ()=>{
  const formRef = React.createRef<FormInstance>()

  // 虚拟键盘同步金额
  const [money, setMoney] = useState<any>("0.00")
  const [keyboardVisible, setKeyboardVisible] = useState<boolean>(false)
  const [timePickerVisible, setTimePickerVisible] = useState<boolean>(false)
  const [needUpdate, setNeedUpdate] = useState(false)

  // 虚拟键盘输入的金额同步到form中
  useEffect(() => {
    const laStr = money.substr(money.length-1, 1)
    if (laStr !== "."){
      formRef.current?.setFieldsValue({
        money: parseFloat(money)
      })
    }
  }, [money]);

  // 检查字符出现频率，用于限制金额输入。仅允许输入一个小数点
  function searchStrIndexOf(target: string) {
    let index = money.indexOf(target)
    let sum = 0;
    while(index > -1) {
      index = money.indexOf(target, index + 1)
      sum ++
    }
    return sum
  }

  // 设置默认的时间
  useEffect(() => {
    formRef.current?.setFieldsValue({
      time: dayjs(new Date()).utc().format()
    })
  }, []);

  return(
    <>
      <Grid columns={2} gap={8}>
        <Grid.Item>
          <a
            style={{color: "green", fontSize: 45,}}
            onClick={()=>{setKeyboardVisible(true)}}
          >￥{money}</a>
        </Grid.Item>
        <Grid.Item>
          <div
            style={{display: "block", height: `100%`}}
            onClick={() => {
              setKeyboardVisible(false)
              setTimePickerVisible(true)
            }}>
            <div style={{textAlign: "right", fontSize: 18}}>时间</div>
            <div style={{textAlign: "right", fontSize: 18, color: "#1677ff"}}>
              <DatePicker
                visible={timePickerVisible}
                precision='minute'
                onCancel={()=>{
                  setTimePickerVisible(false)
                }}
                onConfirm={(val)=>{
                  console.log(val.toString())
                  console.log(dayjs(val).utc().format())
                  formRef.current?.setFieldsValue({
                    time: dayjs(val).utc().format()
                  })
                  setTimePickerVisible(false)
                }}
              >
                {value =>
                  value ? dayjs(value).format('YYYY-MM-DD HH:mm') : dayjs(new Date()).format("YYYY-MM-DD HH:mm")
                }
              </DatePicker>
            </div>
          </div>
        </Grid.Item>
      </Grid>
      <Form
        ref={formRef}
        style={{
          // @ts-ignore
          "---border-bottom": "none",
        }}
        onFinish={async (value)=>{
          if (parseFloat(value.money) == 0 || isNaN(value.money)) {
            Toast.show({
              content: "请输入金额！",
              icon: "fail"
            })
          }else if(value.toWho == "" || value.toWho == undefined){
            Toast.show({
              content: "借给谁了？"
            })
          }else {

            // 提交到数据库
            const success = await handleAdd(value);
            if (success) {
              // 保存成功
              // 重置表单数据
              setMoney("0.00")
              setNeedUpdate(!needUpdate)
            }
          }
          console.log(value)
        }}
      >
        <Form.Item noStyle name={"money"}/>
        <Form.Item noStyle name={"time"}/>
        <Form.Item name={"toWho"} label={"借给谁"}>
          <Input placeholder={"借给谁的"}/>
        </Form.Item>
        <Form.Item name={"remark"} label={"备注"}>
          <Input placeholder={"说明，备注"}/>
        </Form.Item>
        <Divider/>
        <Button
          type='submit'
          shape={"rounded"}
          style={{backgroundColor: "#fa541c", color: "white", fontSize: 15, paddingRight: 30, paddingLeft: 30}}
          size='large'
        >
          记一笔
        </Button>
      </Form>
      <NumberKeyboard
        visible={keyboardVisible}
        onInput={(value)=>{
          // 判断是否输入多个小数点
          const dotCount = searchStrIndexOf(".")
          if (dotCount == 1 && value === "."){
            return
          }

          // 判断是否是初始值
          if (money === "0.00"){
            // 初始输入时，首位不能是小数点
            if (value === "."){
              return;
            }else {
              setMoney(value)
            }
          }else {
            const moneyStr = money + value;
            setMoney(moneyStr)
          }
        }}
        onDelete={()=>{
          if (money !== "0.00"){
            const moneyStr = money.substr(0, money.length - 1)
            setMoney(moneyStr)
          }
        }}
        onClose={()=>{setKeyboardVisible(false)}}
        onConfirm={()=>{setKeyboardVisible(false)}}
        showCloseButton={true}
        customKey="."
        confirmText='确定'
      />
      <Button style={{
        backgroundColor: "#1677ff",
        color: "white",
        width: `calc(100vw - 40px)`,
        height: 58,
        borderTopLeftRadius: 25,
        borderTopRightRadius: 25,
        marginTop: 16
      }}
      ><HandPayCircleOutline /> 借出清单</Button>
      <div style={{width: `calc(100vw - 40px)`}}>
        <LendLogs update={needUpdate}/>
      </div>
    </>
  )
}

export default OwnForm;
